using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

using Quartz;

namespace Util.QuartzNet
{
    public class JobRequestApi : IJob
    {
        private string jobNo = string.Empty;
        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                jobNo = context.JobDetail.JobDataMap.GetString("no");
                string method = context.JobDetail.JobDataMap.GetString("method");
                string url = context.JobDetail.JobDataMap.GetString("url");
                string param = context.JobDetail.JobDataMap.GetString("param");
                HttpClient client = new HttpClient();
                switch (method.ToLower())
                {
                    case "post":
                        {
                            List<KeyValuePair<string, string>> paramsInfo = new List<KeyValuePair<string, string>>();
                            if (param != null)
                            {
                                string[] paramArr = param.Split(new string[] { "&" }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (var item in paramArr)
                                {
                                    string[] itemArr = item.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                                    if (itemArr.Length > 1)
                                    {
                                        paramsInfo.Add(new KeyValuePair<string, string>(itemArr[0], itemArr[1]));
                                    }
                                    else
                                    {
                                        paramsInfo.Add(new KeyValuePair<string, string>(itemArr[0], ""));
                                    }
                                }
                            }
                            HttpContent content = new FormUrlEncodedContent(paramsInfo);
                            var response = await client.PostAsync(url, content);
                            var result = await response.Content.ReadAsStringAsync();
                            WriteLog(LogType.Success, result);
                        }
                        break;
                    case "get":
                        {
                            url = $"{url}{(url.IndexOf("?") > -1 ? "&" : "?")}{param}";
                            var response = await client.GetAsync(url);
                            var result = await response.Content.ReadAsStringAsync();
                            WriteLog(LogType.Success, result);
                        }
                        break;
                    default:
                        WriteLog(LogType.Error, "请求方法异常");
                        break;
                }
            }
            catch (Exception ex)
            {
                WriteLog(LogType.Error, ex.Message);
            }
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="message">日志内容</param>
        /// <returns></returns>
        private void WriteLog(LogType logType, string message)
        {
            string path = $"Log/{jobNo}";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            File.AppendAllText($"{path}/{DateTime.Now:yyyy-MM-dd}.log", $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}][{logType}]{message}\r\n");
        }
    }
}
